'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { updateOauthClientApiByApiId } from '@/services/api';
import diff from 'microdiff';
import {
  OAUTH_CLIENT_API_TYPE_KEY,
  OAUTH_CLIENT_API_TYPE_LIST,
} from '@/lib/constant';
import type {
  IDifference,
  IOauthClientApi,
  IUpdateOauthClientApiByApiIdBody,
} from '@/interfaces';
import type { TBody, TOauthClientApiType } from '@/types';
import useToast from '@/hooks/useToast';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateOauthClientApiInfo(
  this: any,
  {
    details,
  }: {
    details: IOauthClientApi;
  },
) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    type: TOauthClientApiType;
    name: string;
    overview?: string;
    category?: string;
    doc?: string;
    upperLimit?: number;
  }>({
    type: 'REQUIRED',
    name: '',
    overview: '',
    category: '',
    doc: '',
    upperLimit: 0,
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const queryClient = useQueryClient();

  const updateOauthClientApiByApiIdMutation = useMutation(
    async (variables: TBody<IUpdateOauthClientApiByApiIdBody>) => {
      await updateOauthClientApiByApiId(variables);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        type: details.type,
        name: details.name,
        overview: details.overview || '',
        category: details.category || '',
        doc: details.doc || '',
        upperLimit: details.upperLimit || 0,
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          type: details.type,
          name: details.name,
          overview: details.overview || '',
          category: details.category || '',
          doc: details.doc || '',
          upperLimit: details.upperLimit || 0,
        },
        {
          type: form.type,
          name: form.name,
          overview: form.overview,
          category: form.category,
          doc: form.doc,
          upperLimit: form.upperLimit,
        },
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(
    e: ChangeEvent<HTMLSelectElement | HTMLInputElement | HTMLTextAreaElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateOauthClientApiByApiIdMutation.mutateAsync({
        id: details.id,
        data: body,
      });
      await queryClient.refetchQueries(
        ['/oauth', '/clients', '/apis'],
        {},
        { throwOnError: true },
      );

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateOauthClientApiByApiIdMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">名称</label>
            <input
              type="text"
              name="name"
              value={form.name}
              onChange={onChangeForm}
              className="form-control"
              aria-label="name"
              placeholder="请输入接口名称（唯一标识），格式要求是英文字母或者加数字、下划线"
            />
          </div>

          <div>
            <label className="form-label">概述</label>
            <input
              type="text"
              name="overview"
              value={form.overview}
              onChange={onChangeForm}
              className="form-control"
              aria-label="overview"
              placeholder="请输入接口概述（简明扼要并且是不重复的）"
            />
          </div>

          <div>
            <label className="form-label">分类</label>
            <input
              type="text"
              name="category"
              value={form.category}
              onChange={onChangeForm}
              className="form-control"
              aria-label="category"
              placeholder="请输入接口分类"
            />
          </div>

          <div>
            <label className="form-label">文档</label>
            <textarea
              rows={1}
              name="doc"
              value={form.doc}
              onChange={onChangeForm}
              className="form-control"
              aria-label="doc"
              placeholder="请输入接口文档地址"
            />
          </div>

          <div>
            <label className="form-label">类型</label>
            <select
              name="type"
              value={form.type}
              onChange={onChangeForm}
              className="form-select"
              aria-label="type"
              placeholder="请选择接口类型"
            >
              {OAUTH_CLIENT_API_TYPE_LIST.map((key) => {
                return (
                  <option key={key} value={key}>
                    {OAUTH_CLIENT_API_TYPE_KEY[key]}
                  </option>
                );
              })}
            </select>
          </div>

          <div>
            <label className="form-label">上限</label>
            <input
              min={0}
              type="number"
              name="upperLimit"
              value={form.upperLimit}
              onChange={onChangeForm}
              className="form-control"
              aria-label="upperLimit"
              placeholder="请输入接口调用上限（0 代表无上限）"
            />
          </div>

          <button
            type="submit"
            disabled={updateOauthClientApiByApiIdMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateOauthClientApiByApiIdMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
